package wheel.conversion;

import wheel.conversion.Converter;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.ServiceLoader;
import java.util.ServiceConfigurationError;

public class ConverterService {
    private static ConverterService instance;
    
    private Map<Class, Converter> converters = 
            new HashMap<Class, Converter>();
    
    public static synchronized ConverterService getInstance() {
        if (instance == null) {
            instance = new ConverterService();
        }
        return instance;
    }
    
    private ConverterService() {
        loadConverters();
    }
    
    private void loadConverters() {
        try {
            ServiceLoader<Converter> loader = ServiceLoader.load(Converter.class);
            for (Converter converter : loader) {
                if (converter != null) {
                    converters.put(converter.getTargetClass(), converter);
                }
            }
        } catch (ServiceConfigurationError e) {
            e.printStackTrace();
        }
    }
    
    public Converter getConverter(Class targetClass) {
        return converters.get(targetClass);
    }
}
